package com.boe.hbd.client.service.support;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import com.boe.hbd.client.service.TextToSpeechService;
import com.shoushuo.android.tts.ITts;

public class TextToSpeechServiceSupport implements TextToSpeechService, ServiceConnection {


	private boolean speakingEngineEnabled = false;
	private boolean initialized = false;
	private ITts tts;

	public void onServiceDisconnected(ComponentName compName) {
		speakingEngineEnabled = false;
		tts = null;
	}

	public void onServiceConnected(ComponentName name, IBinder service) {
		tts = ITts.Stub.asInterface(service);
		try {
			tts.initialize();
			speakingEngineEnabled = true;
		} catch (RemoteException e) {
		}
	}

	public boolean isInitialized() {
		return initialized;
	}

	public void initialize(Context context) {
		if (!initialized) {
			String actionName = "com.shoushuo.android.tts.intent.action.InvokeTts";
			Intent intent = new Intent(actionName);
			context.bindService(intent, this, Context.BIND_AUTO_CREATE);
			initialized = true;
		}
	}

	public void pause(Context context) {
	}

	public void resume(Context context) {
	}

	public void destroy(Context context) {
		if (speakingEngineEnabled && tts != null) {
			try {
				context.unbindService(this);
			} catch (Throwable e) {
				Log.e("TTS",e.getMessage());
			}
		}
	}

	public void say(String text) {
		if (text != null && !text.equals("") && speakingEngineEnabled) {
			try {
				tts.speak(text, TextToSpeech.QUEUE_FLUSH);
			} catch (RemoteException e) {
				Log.e("TTS",e.getMessage());
			}
		}
	}

}
